import { v4 as uuid } from 'uuid'
import { Message } from 'element-ui'
import { debounce } from 'lodash'
import tinymce from 'tinymce/tinymce'
import registerEvents from './events'
import registerCommands from './commands'
import Socket from './socket'
import {
  addRevisionLines,
  prependChild,
  onNewBlock,
  onPaste,
  addSetupListeners,
  refreshPageNumberInHeader
} from './dom'
import { checkBeforeInsert, handleKeyword, scrollPageByData, sleep, emit } from './helpers'
import { contentTypes, isListTitle, contentPrototypes } from '@/constants/structure'
import { defaultDataTypes } from '@/constants/structure'
import store from '../store'
import { fetchData, getTermInfo, getDependFileType, getRuleInfoAll, uploadFile } from '@/api'
import { refreshTableNumbers } from '@/utils/plugins/table/noteSetting'
import { refreshFigureNumbers } from '@/utils/plugins/image/figureSetting'
import { StdPage } from '@/utils/parse/page'
import dayjs from 'dayjs'
import watermark from 'watermark-dom'
import { getRulesList, getTemplateInfo, getTemplateTree, getTemplateList } from "@/api/business";
import { getAlgoList, loadVaribles } from "@/api/computingConfig.js";
import { getDocumentVariableList } from "@/api/variable";

/** 设置两侧侧边栏 */
async function renderSidebars(editor) {
  const body = editor.getContainer().querySelector('.tox-sidebar-wrap')
  const zoomSlider = document.querySelector('.zoomslider')
  body.appendChild(zoomSlider)

  // 在页面顶部菜单栏插入logo
  const menubar = editor.getContainer()?.querySelector('.tox-menubar')
  const logo = editor.dom.createFragment(` <img src="/assets/logo-header.png" />`)
  const imgExist = editor.getContainer()?.querySelector('.tox-menubar img')
  !imgExist && prependChild(logo, menubar) // 不存在时才添加
  if (store.getters.entry === 'htmlpreview') {
    // 如果_iframe有值，表示用于引用标准内容勾选的显示
    !store.getters._iframe && prependChild(document.querySelector('.slot-component.left-sidebar'), body)
    editor.getContainer()?.classList.add('htmlpreview')
    editor.getDoc()?.querySelector('body#tinymce')?.classList.add('pageless')
    await sleep()
    store.commit('xmleditor/SET_PAGE_PURE_HTML') // html预览的文档设置可编辑
  } else if (store.getters.leftSidebarItems.length) {
    prependChild(document.querySelector('.slot-component.left-sidebar'), body)
    await sleep()
    store.commit('xmleditor/SET_PAGE_NONEDITABLE') // 正常编辑的文档设置不可编辑
  }

  store.commit('xmleditor/UPDATE_DOC_STRUCTURE')

  body.appendChild(document.querySelector('.slot-component.right-sidebar'))
}

function onUndoRedo(editor) {
  const cb = debounce(() => store.commit('xmleditor/UPDATE_DOC_STRUCTURE'), 600)
  editor.on('Redo', cb)
  editor.on('Undo', cb)
}

/** 监听光标处于正文内容中时，左侧结构树对应层级将高亮显示 */
function onListTitleFocused(editor) {
  editor.on('click', ({ target, stopPropagation }) => {
    let targetId = null
    if (tinymce.DOM.is(target, '.list-title')) {
      targetId = target.dataset.id
    } else {
      let parent = target
      if (!tinymce.DOM.is(target, '.page-sheet')) {
        parent = editor.dom.getParent(target, '.page-sheet')
      }
      if (tinymce.DOM.is(parent, '.page-sheet[data-content-page-type="blank_page"]')) {
        targetId = null
      } else {
        targetId = parent?.dataset?.pageId
      }
    }
    store.commit('xmleditor/SET_FOCUSED_LIST_TITLE', targetId)
    stopPropagation()
  })
}

function onContentsRowClick(editor) {
  const handler = function (e) {
    let target = e.target
    if (!editor.dom.is(target, '.link-row')) {
      target = editor.dom.getParent(target, '.link-row')
      if (!target) {
        return
      }
    }
    const { referredId, linkType } = target.dataset
    scrollPageByData({ dataId: referredId, dataType: linkType })
  }
  editor.getDoc()?.addEventListener('click', handler)
  editor.on('click', handler)
}

function onRefLineClick(editor) {
  const handler = function (e) {
    emit('editor-click')
    let target = e.target

    if (editor.dom.is(target, '.ref-link:not(.ref-disabled)')) {
      const linkUrl = target?.dataset?.linkUrl
      if (linkUrl) {
        const open = window.open()
        open.location = linkUrl
        return
      }
    } else if (editor.dom.is(target?.parentNode, '.ref-link:not(.ref-disabled)')) {
      const linkUrl = target?.parentNode?.dataset?.linkUrl
      if (linkUrl) {
        const open = window.open()
        open.location = linkUrl
        return
      }
    }
    // if (editor.dom.is(target, '[data-docno]:not(.ref-disabled)')) {
    //   if (editor.dom.is(target, '[data-content-page-type="terms_definitions"] p')) {
    //     return
    //   }
    //   const docNo = target.dataset.docno
    //   if (docNo) {
    //     const open = window.open()
    //     const search = `?editContentType=document&entry=htmlpreview&docNo=${docNo}`
    //     const anchor = target.dataset.refanchor ? `#${target.dataset.refanchor}` : ''
    //     open.location = window.location.origin + '/editor/view' + search + anchor
    //     return
    //   }
    //   console.warn('===错误的docno===')
    // }
  }
  editor.getDoc()?.addEventListener('click', handler)
  editor.on('click', handler)
}

/** 插入复选框符号，并对符号双击可切换 */
function onCheckCharDblClick(editor) {
  editor.on('dblclick', function () {
    const { collapsed, startContainer, endContainer, startOffset, endOffset } = editor.selection.getRng() || {}
    if (!collapsed) {
      if (startContainer === endContainer) {
        if (startContainer.nodeType === 3) {
          if (startOffset + 1 === endOffset) {
            const char = startContainer.nodeValue.substring(startOffset, endOffset)
            if (char === '☐') {
              editor.execCommand('mceInsertContent', false, '☑')
            } else if (char === '☑') {
              editor.execCommand('mceInsertContent', false, '☐')
            }
          }
        }
      }
    }
  })
}
// 点击contenteditable="false"内容移动光标位置
function onContenteditableFalseClick(editor) {
  editor.on('click', function (e) {
    let target = e.target
    const termBlock = editor.dom.getParent(target, '[data-type="terms"]')
    if (termBlock) {
      target = termBlock
    }
    const nakedFigureBlock = editor.dom.getParent(target, '[data-type="naked_figure"]')
    if (nakedFigureBlock) {
      target = nakedFigureBlock
    }
    const nakedFigure = '[data-type="naked_figure"]'
    const listTitle = 'p.list-title[contenteditable="false"]'
    const nrGuide = '[data-content-page-type="normative_references"]>.page_body p[contenteditable="false"]'
    const termGuide = '[data-content-page-type="terms_definitions"]>.page_body p[contenteditable="false"]'
    const abbrGuide = '[data-content-page-type="symbols_abbreviation"]>.page_body p[contenteditable="false"]'
    const abbrTable = editor.dom.getParent(target, 'table.abbr-table')
    if (abbrTable) {
      target = abbrTable
    }
    const selectorStr = `${nakedFigure},[data-type="terms"], ${listTitle},${nrGuide},${termGuide},${abbrGuide},table.abbr-table`
    if (editor.dom.is(target, selectorStr)) {
      const childNodes = target.parentNode?.childNodes || []
      let pos = 0
      for (let i = 0; i < childNodes.length; i++) {
        const el = childNodes[i]
        if (el === target) {
          pos = i
          break
        }
      }
      editor.selection.setCursorLocation(target.parentNode, pos + 1)
    }
  })
}

function onIframeCheckboxClicked(editor) {
  editor.getDoc()?.addEventListener('click', (e) => {
    const target = e.target
    const isCheckbox = editor.dom.is(target, '[data-iframe-checkbox] input')
    if (isCheckbox) {
      const parent = editor.dom.getParent(target, '[data-iframe-checkbox]')
      const span = parent.querySelector('span.el-checkbox__input')
      if (editor.dom.is(parent, '.is-checked')) {
        editor.dom.removeClass(parent, 'is-checked')
        editor.dom.removeClass(span, 'is-checked')
      } else {
        editor.dom.addClass(parent, 'is-checked')
        editor.dom.addClass(span, 'is-checked')
      }
    }
  })
}

function scrollByHash() {
  const hash = window.location.hash
  if (/^#a_[a-z0-9_]{36}$/g.test(hash)) {
    const blockId = hash.match(/#a_([a-z0-9_]{36})/)[1].replace(/_/g, '-')
    scrollPageByData({ trigger: 'hash', blockId })
  }
}

/** 编辑器开始 */
export function setup(editor) {
  addSetupListeners(editor)
  onNewBlock(editor)
  onPaste(editor)

  // 删除公式
  editor.on('keydown', (event) => {
    const formulaNode = editor.dom.getParent(editor.selection.getNode(), '[data-type="formula"]')
    const getNode = (el) => (tinymce.DOM.is(el, '[data-type="formula"]') ? el : null)
    const checkRefNode = (el) => tinymce.DOM.is(el, 'span[data-type="refdoc"],span[data-type="refchapter"]')
    const handler = (elm) => {
      editor.dom.remove(elm)
      editor.fire('updateFormulaNumber')
    }

    // 如果光标在公式内部
    if (formulaNode) {
      if (event.key === 'Backspace' || event.key === 'Delete') {
        handler(formulaNode)
      }
    } else {
      const { startContainer, endContainer, commonAncestorContainer } = editor.selection.getRng() || {}
      // 如果公式在光标前面
      if (event.key === 'Backspace') {
        const formulaNode = getNode(startContainer)
        if (formulaNode) {
          handler(formulaNode)
          return
        }

        // 前面是引用
        if (checkRefNode(startContainer?.previousElementSibling)) {
          return editor.fire('removeRef', { node: startContainer?.previousElementSibling })
        }
      }
      // 如果公式在光标后面
      if (event.key === 'Delete') {
        if (getNode(endContainer)) {
          if (formulaNode) {
            handler(formulaNode)
          }
          return
        }

        if (checkRefNode(endContainer?.nextElementSibling)) {
          return editor.fire('removeRef', { node: endContainer?.nextElementSibling })
        }
      }

      if (event.key === 'Backspace' || event.key === 'Delete') {
        // 选中内容中删除
        const childNodes = [...commonAncestorContainer?.childNodes]
        if (childNodes.some((node) => checkRefNode(node))) {
          editor.fire('removeRef', { nodes: childNodes.filter((node) => checkRefNode(node)) })
        }
      }
    }
  })
  // 自定义命令
  registerCommands(editor)
  // editor.on('click', function (e) {
  //   // 处理点击事件

  //   if(e.srcElement.dataset.type === 'variable_formula'){
  //     store.commit('xmleditor/SET_EDITING_FORMULA', { id: null, type: null })
  //     var baseURL =tinymce.baseURL + '/tinymce/plugins/kityformula/index.html'
  //     const buttons = [{ type: 'cancel', text: 'Close' },{ type: 'custom', text: '保存', name: 'save', primary: true }]
  //     editor.windowManager.openUrl({
  //       title:'插入公式',
  //       size: 'large',
  //       width: 850,
  //       height: 500,
  //       url: baseURL,
  //       buttons,
  //       onAction: function (api, details) {
  //         if (!checkBeforeInsert('formula')) return
  //         api.sendMessage('save')
  //       }
  //     })
  //   }else if(e.srcElement.dataset.type === 'variable_inline_formula'){
  //     store.commit('xmleditor/SET_EDITING_FORMULA', { id: null, type: null })
  //     var baseURL =tinymce.baseURL + '/tinymce/plugins/kityformula/index.html'
  //     const buttons = [{ type: 'cancel', text: 'Close' },{ type: 'custom', text: '保存', name: 'inline_formula', primary: true }]
  //     editor.windowManager.openUrl({
  //       title:'插入行内公式',
  //       size: 'large',
  //       width: 850,
  //       height: 500,
  //       url: baseURL,
  //       buttons,
  //       onAction: function (api, details) {
  //         if (!checkBeforeInsert('inline_formula')) return
  //         api.sendMessage('save_inline_formula')
  //       }
  //     })
  //   }
  // });
}

/** 初始化 websocket */
function initSocket() {
  //const url = 'ws://' + window.location.host + '/'
  const url = 'ws://' + window.location.host
  const { userNo, docNo } = store.state.xmleditor.originalEditorConfig || {}
  new Socket({ url, userNo, docNo })
}

export async function images_upload_handler(blobInfo, success) {
  const formData = new FormData()
  formData.append('file', blobInfo.blob(), blobInfo.filename())
  try {
    const { data: ossId } = await uploadFile(formData)
    success(window.location.origin + '/prod-api/editor/file/download/' + ossId)
    // success('http://172.16.41.11/prod-api/editor/file/download/' + ossId)
  } catch (error) {
    console.log(error)
  }
}

/** 实例初始化后 */
export async function init_instance_callback(editor) {
  registerEvents(editor)
  getDependFileType()
  await fetchEditorData()
  await sleep()
  if (['document', 'template'].includes(store.getters.editContentType)) {
    onContentsRowClick(editor)
  }
  if (store.getters.collaborate) {
    initSocket()
  }
  renderSidebars(editor)
  onUndoRedo(editor)
  editor.save() // 用于设置 tinymce.activeEditor.isDirty() 为 false

  addRevisionLines(editor)

  onListTitleFocused(editor)
  onRefLineClick(editor)
  onCheckCharDblClick(editor)
  onContenteditableFalseClick(editor)
  if (store.getters._iframe) {
    onIframeCheckboxClicked(editor)
  }
  scrollByHash() //引用的内容可能带以 a_ 开头的hash
  handleKeyword(editor)

  // 设置只读模式
  const entry = store.getters.entry
  if (entry === 'preview' || entry === 'htmlpreview' || entry === 'termpreview') {
    tinymce.activeEditor.mode.set('readonly')
  }
  if (entry === 'preview' || entry === 'termpreview') {
    console.log(editor.getDoc().querySelector('body'))
    const { userName, userNo } = store.state.xmleditor.currentUserInfo || {}
    const date = dayjs().format('YYYY-MM-DD')
    const watermark_txt = `本文档禁止截图、拍照！当前阅读人${userName}(${userNo}) ${date}`
    watermark.load({
      watermark_txt,
      watermark_width: 500,
      watermark_height: 200,
      watermark_angle: 45
    })
  }

  // 显示特殊字符前判断是否光标在页面中
  editor.on('BeforeExecCommand', (p) => {
    if (p.command === 'mceShowCharmap' && !checkBeforeInsert('charmap')) {
      return false
    }
    // 上下标不在禁止编辑页面使用
    if (p.command === 'mceToggleFormat' && ['superscript', 'subscript'].indexOf(p.value) > -1) {
      if (!checkBeforeInsert(p.value)) return false
    }
  })
  // 中文输入有 composition 过程
  editor.on('compositionend', editor.undoManager.add)

  // 光标位置在标题内则更新标题
  const updateTitleHandler = () => {
    if (editor.dom.getParent(editor.selection.getNode(), '.list-title, .annex-title')) {
      store.commit('xmleditor/UPDATE_DOC_STRUCTURE')
    }
  }

  editor.on('input', debounce(updateTitleHandler, 400))
  refreshPageNumberInHeader(editor)
  refreshFigureNumbers(editor)
  refreshTableNumbers(editor)

  // 避免将最初的内容撤销掉
  setTimeout(() => editor.undoManager.clear())
}

/**
 * 从服务器获取编辑器内容
 */
async function fetchEditorData() {
  const { commit } = store
  /** ------------------- 获取术语begin---------------------- */
  const { editContentType, entry } = store.getters
  if (editContentType === 'block' && (entry === 'termblock' || entry === 'termpreview')) {
    const id = store.state.xmleditor?.editorConfig?.id
    if (!id) {
      return Message.error('错误的术语id')
    }
    const res = await getTermInfo(id)
    let jsonContent = []
    try {
      if (res?.data?.jsonContent) {
        jsonContent = JSON.parse(res?.data?.jsonContent || '[]')
      } else {
        const createPara = (content) => ({
          blockId: uuid(),
          blockType: 'block',
          dataType: 'paragraph',
          textData: {
            dataId: uuid(),
            contentList: [{ contentType: 'text', content, fullContent: content }]
          }
        })
        jsonContent = [createPara(res?.data?.description || '')]
        if (res?.data?.descriptionEn) {
          jsonContent.push(createPara(res?.data?.descriptionEn))
        }
      }
      console.debug('---INIT_BLOCK_DATA---', jsonContent)
    } catch (error) {
      return Message.error('文档数据错误')
    }
    commit('xmleditor/INIT_EDITOR_DATA', jsonContent)
    return
  }
  /** ------------------- 获取术语end---------------------- */

  let data = await fetchData()
  // 缓存文章信息
  commit('xmleditor/SET_DOC_INFO', data?.data || {});
  // 查询文章类型
  const rules = await getRulesList();
  const useRule = await rules?.data.filter(item => {
    return item.name === 'BLANK'
  })
  if (data?.data?.ruleId === useRule[0].id) {
    const algoTempalteEmpty = data?.data?.jsonContent ? false : true;
    // true则用模板数据覆盖
    if (algoTempalteEmpty) {
      //查询算例模板数据
      await getTemplateTree().then(async res => {
        if (res?.data) {
          let algoTemplate = await res?.data[0]?.children.filter(item => {
            return item.name.includes('算例模板')
          }) || [];
          let tempalteChild = algoTemplate[0].children;
          let stressTemplateId = tempalteChild[0]?.id;
          //查询模板文章信息
          await getTemplateList({
            classifyId: stressTemplateId,
            pageNum: 1,
            pageSize: 100
          })
            .then(async (res) => {
              const dataList = await res.data.list.map(i => {
                return {
                  ...i,
                  isPublished: i.status === '1'
                }
              })
              const templateInfo = await dataList.filter(item => {
                return item.name === '算例模板'
              })
              const result = await getTemplateInfo(templateInfo[0].id)
              data = { ...result };
            })

        }
      })
    }
  }
  if (data?.data?.ruleId) {
    commit('xmleditor/SET_RULE_ID', data?.data?.ruleId)
    getRuleInfoAll(data?.data?.ruleId).then((res) => {
      commit('xmleditor/SET_RULE_STRUCTURES', res?.structures)
      commit('xmleditor/SET_RULE_FONTS', res?.fonts)
    })
  } else if (store.getters.editContentType !== 'block' && store.getters.editContentType !== 'collect') {
    Message.error('没有ruleId，请联系管理员')
  }

  let jsonContent = null

  if (store.getters.editContentType === 'block' || store.getters.editContentType === 'collect') {
    try {
      jsonContent = JSON.parse(data.data.jsonContent || '[]')
      console.debug('---INIT_BLOCK_DATA---', jsonContent)
    } catch (error) {
      return Message.error('文档数据错误')
    }
    commit('xmleditor/SET_LANGUAGE_TYPE', data?.data?.languageType || 'zh')
    commit('xmleditor/INIT_EDITOR_DATA', jsonContent)
    return
  }

  try {
    jsonContent = JSON.parse(data.data.jsonContent || '[]')
  } catch (error) {
    return Message.error('文档数据错误')
  }

  // 需要放在INIT_EDITOR_DATA前面是因为可能会覆盖其内容
  commit('xmleditor/SET_EDITABLE_IDS', data?.data?.editableIds || [])

  if (data?.data?.isChief || data?.data?.editableIds?.length) {
    commit('xmleditor/SET_CAN_SAVE')
  }

  commit('xmleditor/SET_LANGUAGE_TYPE', data?.data?.languageType || 'zh')
  // 是否是自动生成报告文章
  let isAlgoDoc = false;
  let algoDocIndex = -1;
  if(jsonContent){
    for (let i = 0; i < jsonContent?.pageList?.length; i++) {
      const page = jsonContent.pageList[i];
      if (page.pageType == 'content') {
        if (page?.blockList[0]?.dataType == 'chapter' && page?.blockList[0]?.textData?.contentList[0]?.content == '强度分析') {
          isAlgoDoc = true;
          algoDocIndex = i;
          break;
        }
      } else {
        continue;
      }
    }
  }
  // 文章编辑时候-算例数据添加
  if (isAlgoDoc && store.getters.editContentType === 'document') {
    //查询算例数据并组装数据
    let algoDatas = [];
    const reportAlgos = store.state.xmleditor.reportAlgos || [];
    await getAlgoList({
      pageNum: 1,
      pageSize: 100
    }).then(async (res) => {
      const list = res?.data?.list || [];
      let queryList= [];
      await reportAlgos.forEach(async(el) => {
        await list.forEach(item=>{
          if(item.id == el){
            queryList.push(item)
          }
        })
      })
      let existVars =  [];
      let existPicVars =  [];
      let existTableVars = [];
      for (let i = 0; i < queryList.length; i++) {
        const result = await getTemplateInfo(queryList[i].templateId);
        // 缓存算例变量
        const templateVarsList = result?.data?.templateVars || [];
        const formulaVarsList =await templateVarsList.filter(el=>{
          return el.variableCode.includes('algo_formula_num');
        })
        const picVarsList =await templateVarsList.filter(el=>{
          return el.variableCode.includes('algo_pic_num');
        })
        const tableVarsList =await templateVarsList.filter(el=>{
          return el.variableCode.includes('algo_table_num');
        })
        existVars = [...existVars,...formulaVarsList]
        existPicVars = [...existPicVars,...picVarsList]
        existTableVars = [...existTableVars,tableVarsList]
        const docData = JSON.parse(result.data.jsonContent || '[]')
        algoDatas.push(docData)
      }
      commit('xmleditor/SET_ALGO_TEMPLATE_VARS', existVars);
      commit('xmleditor/SET_ALGO_PIC_VARS', existPicVars);
      commit('xmleditor/SET_ALGO_TABLE_VARS', existTableVars);
      
    })
    // 填充数据
    if (jsonContent.pageList[algoDocIndex].blockList.length <= 2) {
      // 添加算例结果
      const queryId = store.state.xmleditor.variableCharptId;
      let algoResultList = [];
      if (queryId) {
        if(store.state.xmleditor.docStatus!=9 && store.state.xmleditor.docStatus!=0){
          await loadVaribles({ docNo: store.state.xmleditor.docInfo.docNo, ids: [Number.parseInt(queryId)] }).then(res => {
            algoResultList = [...res?.data]
          })
        }
      }
      for (let i = 0; i < algoDatas.length; i++) {
        const blockData = algoDatas[i].pageList[0].blockList;
        let indexStart = 0;
        let indexEnd = 0;
        for (let i = 0; i < blockData.length; i++) {
          if (blockData[i].blockIndex === '1.2') {
            indexStart = i;
          }
          if (blockData[i].blockIndex === '1.5') {
            indexEnd = i;
          }
        }
        let finalData = [blockData[0]]
        for (let i = indexStart; i < indexEnd; i++) {
          finalData.push(blockData[i]);
        }
        //处理数据
        finalData.forEach(item => {
          if (item) {
            item.blockId = uuid();
            if (item?.textData?.dataId) {
              item.textData.dataId = uuid();
            }
            if (item?.tableData?.dataId) {
              item.tableData.dataId = uuid();
            }

            if (item.dataType === 'item1') {
              item.dataType = 'item2'
            }
            if (item.dataType === 'chapter') {
              item.dataType = 'item1'
            }
          }
        })
        if (finalData.length > 0) {
          jsonContent.pageList[algoDocIndex].blockList = [...jsonContent.pageList[algoDocIndex].blockList, ...finalData];
        }

        // 添加算例结果
        if (algoResultList.length>0) {
          let resultTemplateJsonData = null;
          resultTemplateJsonData = algoResultList[0]?.variableContent[i]?.resultJsonContent;
          const resultTemplateDocData = JSON.parse(resultTemplateJsonData || '[]')
          const resultTemplateBlockData = resultTemplateDocData.pageList[0].blockList;
          //处理数据
         await resultTemplateBlockData.forEach(el => {
            if (el) {
              el.blockId = uuid();
              if (el?.textData?.dataId) {
                el.textData.dataId = uuid();
              }
              if (el?.tableData?.dataId) {
                el.tableData.dataId = uuid();
              }

              if (el.dataType.trim() === 'item1') {
                el.dataType = 'item3'
              }
              if (el.dataType.trim() === 'chapter') {
                el.dataType = 'item2'
              }
            }
          })
         jsonContent.pageList[algoDocIndex].blockList = [...jsonContent.pageList[algoDocIndex].blockList, ...resultTemplateBlockData];
        }
      }
    }
  }
  if (jsonContent) {
    console.debug('---INIT_EDITOR_DATA---', jsonContent)
    commit('xmleditor/SET_DOCTYPE', jsonContent?.docType)
    commit('xmleditor/INIT_EDITOR_DATA', jsonContent)
  }

  // 后端传回是否是术语、缩略语文档
  const prop = data?.data?.fileProperty
  commit('xmleditor/SET_FILE_PROPERTY_NAME', prop)
  commit('xmleditor/SET_ISCHIEF', data?.data?.isChief)
  commit('xmleditor/SET_CURRENT_USERINFO', data?.data?.currentUserInfo)
  commit('xmleditor/SET_DOC_SOURCE', data?.data?.source || 1) // source: 1 平台新增，2 文件解析
  commit('xmleditor/SET_HAS_PRE_CHANGE_FILES', data?.data?.hasPreChangeFiles)
  commit('xmleditor/SET_PUBLIC_FILE_PATH', data?.data?.publicFilePath)
  commit('xmleditor/SET_TEMPLATE_ID', data?.data?.templateId)
  commit('xmleditor/SET_STANDARD_BASE_INFO', data?.data?.standardBaseInfo)
  commit('xmleditor/SET_REVISION_LINE_IDS', data?.data?.revisionLineIds || [])
  commit('xmleditor/SET_REVISION_LINE_ENABLE', !!data?.data?.enableRevisionLine)
  commit('xmleditor/SET_SIGNATURE_USERS', data?.data?.revisionAndSignatureInfo?.signatureUserList || [])
  commit('xmleditor/SET_SIGNATURE_INFO', data?.data?.revisionAndSignatureInfo?.signatureInfoList || [])
  commit('xmleditor/SET_REVISION', data?.data?.revisionAndSignatureInfo?.revisionContentList || [])
  commit('xmleditor/SET_PERMISSIONS', data?.data?.permissions || {})
}
export function getInitPageList(data) {
  // 不自动填充封面、签署页、修改记录页
  // if (data.pageList.every((i) => i.pageType !== 'revision')) {
  //   data.pageList.unshift(new StdPage({ pageType: 'revision' }))
  // }
  // if (data.pageList.every((i) => i.pageType !== 'signature')) {
  //   data.pageList.unshift(new StdPage({ pageType: 'signature' }))
  // }
  // if (data.pageList.every((i) => i.pageType !== 'cover')) {
  //   data.pageList.unshift(new StdPage({ pageType: 'cover' }))
  // }
  const termList = []
  let lastPageEditable = false // 空白页前的章节页是否可编辑
  for (const page of data?.pageList) {
    const { pageId, pageType, blockList } = page
    if (pageType === 'content') {
      const pageContentType = blockList[0]?.dataType
      if (contentTypes.includes(pageContentType)) {
        lastPageEditable = store.state.xmleditor.editableIds.includes(pageId)
      } else if (pageContentType === 'blank_page') {
        if (lastPageEditable) {
          store.commit('xmleditor/ADD_NEW_PAGE_EDITABLE', pageId)
        } else {
          store.commit('xmleditor/REMOVE_PAGE_EDITABLE', pageId)
        }
      } else {
        console.warn('错误的正文类型')
      }
    }
    page?.blockList?.forEach((block) => {
      if (block?.dataType === 'terms') {
        termList.push(block)
      }
      if (block?.dataType === 'abbreviation') {
        store.commit('xmleditor/SET_ABBR_TABLE_DATA', block)
      }
      // 中英文添加英文
      if (isListTitle(block?.dataType)) {
        const proto = contentPrototypes.find((i) => i.dataType === block?.dataType)
        if (data.languageType === 'both') {
          if (defaultDataTypes.includes(block?.dataType)) {
            block.textData.contentList[0].content = proto.label
            block.textData.contentList[0].contentEn = proto.labelEn
            block.textData.contentList[0].fullContent = `${proto.label}(${proto.labelEn})`
          } else {
            const defaultContentEn = block?.dataType === 'chapter' ? '' : proto?.labelEn || ''
            block.textData.contentList[0].contentEn =
              block?.textData?.contentList?.[0]?.contentEn || defaultContentEn
          }
        } else {
          if (defaultDataTypes.includes(block?.dataType)) {
            block.textData.contentList[0].content = proto.label
            block.textData.contentList[0].fullContent = proto.label
          }
        }
      }
    })
  }
  store.commit('xmleditor/SET_TERM_BLOCK_LIST', termList)
  if (termList.length) {
    // 对保存的层级进行回显
    store.commit('xmleditor/SET_TERM_LIST_TITLE_TYPE', 'item' + (termList[0]?.termData?.contentNumber?.split('.')?.length - 1))
  }

  return data?.pageList?.map((i) => new StdPage(i)) || []
}
